const app = getApp()
//获得全局js变量
var util = require('../../../../utils/util.js');
Page({
    data: {
        cardId: null,
        formData: {
            name: '',
            branchName: '',  // 开户行
            bankName: '',
            cardNumber: '',
            phone: ''
        },
        submitDisabled: true
    },
    
    onLoad: function(options) {
        // 获取传递过来的银行卡ID
        this.setData({
            cardId: options.id
        });
        
        // 获取上一个页面传递的银行卡数据
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on('acceptCardData', (data) => {
            const card = data.card;
            this.setData({
                formData: {
                    name: card.name || '',
                    branchName: card.opbank || '',
                    bankName: card.banktype || '',
                    cardNumber: card.cardnum || '',
                    phone: card.phone || ''
                },
                submitDisabled: false  // 如果有数据，默认启用提交按钮
            });
        });
    },
    
    // 输入框内容变化
    inputChange: function(e) {
        const { field } = e.currentTarget.dataset;
        const { value } = e.detail;
        
        this.setData({
            [`formData.${field}`]: value
        });
        
        this.checkFormValid();
    },
    
    // 检查表单是否有效
    checkFormValid: function() {
        const { name, branchName, bankName, cardNumber, phone } = this.data.formData;
        const isValid = name && branchName && bankName && cardNumber && phone;
        
        this.setData({
            submitDisabled: !isValid
        });
    },
    
    // 提交表单
    submitForm: function() {
        if (this.data.submitDisabled) {
            return;
        }
        
        const that = this;
        wx.showLoading({
            title: '保存中...',
        });
        
        // 构建请求参数
        const params = {
            ...this.data.formData,
            cardId: this.data.cardId
        };
        
        util.httpRrquest(app.data.rooturl + 'user/updateBankCard', 'POST', params)
        .then(function (response) {
            wx.hideLoading();
            
            if (response.data.code == 1) {
                wx.showToast({
                    title: '修改成功',
                    icon: 'success'
                });
                
                // 延迟返回上一页，让用户看到成功提示
                setTimeout(() => {
                    wx.navigateBack();
                }, 1500);
            } else {
                wx.showToast({
                    title: response.data.msg || '修改失败',
                    icon: 'none'
                });
            }
        }, function (error) {
            wx.hideLoading();
            console.log(error);
            wx.showToast({
                title: '网络错误，请重试',
                icon: 'none'
            });
        });
    }
})